package wz

import (
	"fmt"
	"github.com/go-resty/resty/v2"
	"github.com/zeromicro/go-zero/core/logx"
	"navi-mumbai/common/xerr"
	"net/http"
	"strconv"
	"time"
)

type AuthReq struct {
	User  string `json:"user"`  // B端用户名称 用户注册账户 邮箱取@之前 最大64字节
	Uid   string `json:"uid"`   // B端用户ID
	Token string `json:"token"` // B端的用户登录Token，单一钱包有效，最大128字节
}

type AuthResp struct {
	Code int    `json:"code"`
	Data string `json:"data"` // G端的用户登录Token，最大128字节
}

const authURI = "wzgames/auth/access_token"

var logger = logx.WithDuration(time.Second)

func (r *HttpClient) Auth(req *AuthReq) (resp *AuthResp, err error) {
	// md5
	// TODO 暂时把token写为固定字符串 因为接口token不超过128字节
	req.Token = "fixedtoken"
	stamp := strconv.FormatInt(time.Now().Unix(), 10)
	sign := md5v(r.Id + req.User + req.Uid + req.Token + stamp + r.Secret)
	resp = &AuthResp{}
	var rsp *resty.Response

	logger.Infof("【B to G Auth】 parameter operator %s user %s uid %s token %s stamp %s sign %s ", r.Id, req.User,
		req.Uid, req.Token, stamp, sign)

	rsp, err = r.cli.R().SetHeader("Accept", "application/json").SetQueryParams(map[string]string{
		"operator": r.Id,
		"user":     req.User,
		"uid":      req.Uid,
		"token":    req.Token,
		"stamp":    stamp,
		"sign":     sign,
	}).SetResult(resp).SetError(resp).Post(r.Host + authURI)

	logger.Infof("【B to G Auth】  rsp %s ", rsp.String())
	logger.Infof("【B to G Auth】  resp %s ", resp.Data)
	if err != nil {
		logger.Infof("【B to G Auth】 error %s ", err.Error())
		return
	}
	if rsp.IsError() {
		logger.Infof("【B to G Auth】 status %s rsp %s ", rsp.Status(), rsp.String())
		err = xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, rsp.Status())
		return
	}
	if resp.Code != http.StatusOK {
		logger.Infof("【B to G Auth】 error code %d data %s ", resp.Code, resp.Data)
		err = xerr.NewGrpcErrCodeMsg(xerr.ThirdPartRequestError, fmt.Sprintf("code:%d", resp.Code))
		return
	}

	return
}
